import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/driver_info_entity.dart';
import 'package:nyh_motorcade_app/entity/vehicle_details_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class VehicleDetailsController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState state = MultiState.loading;
  MultiState multiState = MultiState.loading;
  String vehicleId = "";
  String motorcadeId = "";
  int page = 1;
  VehicleDetailsEntity? entity;
  int orderCount = 0;
  List<DriverInfoItem> driverInfoList = [];

  @override
  void onReady() {
    super.onReady();
    vehicleId = Get.arguments ?? "";
    getVehicleDetails();
  }

  Future<void> onRefresh() async {
    page = 1;
    getBindDriverList();
  }

  Future<void> onLoading() async {
    getBindDriverList();
  }

  void onRetry() {
    driverInfoList.clear();
    page = 1;
    multiState = MultiState.loading;
    update();
    getBindDriverList();
  }

  void onRetryAll() {
    page = 1;
    state = MultiState.loading;
    update();
    getVehicleDetails();
  }

  void goBackHomePage() {
    Get.until((route) => Get.currentRoute == Routes.main);
  }

  Future<void> goToBindDriverPage() async {
    if (vehicleId.isEmpty || entity == null) {
      return;
    }
    dynamic data = await Get.toNamed(Routes.bindDriver, arguments: {
      Constant.PARAM_TYPE: Constant.VEHICLE_BIND_DRIVER,
      Constant.PARAM_SOURCE_ID: vehicleId,
      Constant.PARAM_MOTORCADE_ID: entity!.motorcadeId ?? "",
    });
    if (data != null) {
      driverInfoList.clear();
      page = 1;
      multiState = MultiState.loading;
      update();
      getBindDriverList();
    }
  }

  Future<void> goToEditVehicleInfoPage() async {
    if (entity == null) {
      return;
    }
    dynamic data = await Get.toNamed(Routes.addVehicle, arguments: {Constant.PARAM_ENTITY: entity, Constant.PARAM_IS_RETURN: true});
    if (data != null) {
      driverInfoList.clear();
      page = 1;
      state = MultiState.loading;
      update();
      getVehicleDetails();
    }
  }

  void goToTransactionFlowPage() {
    Get.toNamed(Routes.transactionFlow, arguments: {Constant.PARAM_TYPE: Constant.VEHICLE, Constant.PARAM_SOURCE_ID: vehicleId});
  }

  void goToDriverDetailsPage(String? id) {
    Get.toNamed(Routes.driverDetails, arguments: id);
  }

  void getVehicleDetails() {
    httpManager.post(
      Get.context,
      HttpAddress.GET_VEHICLE_DETAILS,
      {"id": vehicleId},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          state = MultiState.fail;
          update();
          return;
        }
        entity = VehicleDetailsEntity().fromJson(data);
        motorcadeId = entity!.motorcadeId ?? "";
        state = MultiState.success;
        update();
        getBindDriverList();
      },
      onFail: (code, msg) {
        state = MultiState.fail;
        update();
      },
      onError: (msg) {
        state = MultiState.error;
        update();
      },
    );
  }

  Future<void> getBindDriverList() async {
    if (motorcadeId.isEmpty) {
      return;
    }
    httpManager.post(
      Get.context,
      HttpAddress.GET_VEHICLE_DETAILS_BIND_DRIVER_LIST,
      {
        "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
        "vehicleId": vehicleId,
        "motorcadeId": motorcadeId,
      },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        DriverInfoEntity driverInfoEntity = DriverInfoEntity().fromJson(data);
        orderCount = driverInfoEntity.total ?? 0;
        List<DriverInfoItem> list = driverInfoEntity.item ?? [];
        if (list.isNotEmpty) {
          multiState = MultiState.success;
          if (refreshController.isRefresh) {
            driverInfoList.clear();
            refreshController.refreshCompleted();
          } else {
            if (list.length >= 10 || page == 1) {
              refreshController.loadComplete();
            } else {
              refreshController.loadNoData();
            }
          }
          if (page == 1) {
            driverInfoList.clear();
          }
          driverInfoList.addAll(list);
          page++;
        } else {
          if (refreshController.isRefresh) {
            refreshController.refreshCompleted();
          } else {
            refreshController.loadNoData();
          }
          if (page == 1) {
            multiState = MultiState.empty;
          }
        }
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        refreshController.loadFailed();
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  void unboundDriver(String? driverId) {
    httpManager.post(
      Get.context,
      HttpAddress.UNBOUND_VEHICLE_DRIVER,
      {
        "vehicleId": vehicleId,
        "driverIds": [driverId],
      },
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("解绑失败");
            return;
          }
          ToastUtils.toast("解绑成功");
          driverInfoList.removeWhere((element) {
            return element.id == driverId;
          });
          multiState = driverInfoList.isNotEmpty ? MultiState.success : MultiState.empty;
          update();
        }
      },
    );
  }
}
